import { createRouter, createWebHistory } from "vue-router";
import page from "@/router/page.js";
import Cookie from "js-cookie";

//按需加载组件
let LoginView = () => import("@/views/Login");
let _404View = () => import("@/views/404");
let IndexView = () => import("@/views/Index");

const routes = [
  {
    //默认主页
    path: "/",
    redirect: "/index/homepage",
  },
  {
    //首页
    path: "/index",
    name: "index",
    redirect: "/index/home",
    component: IndexView,
    children: [
      ...page,
      {
        path: "flush",
        name: "flush",
        component: () => import("@/views/Flush"),
        meta: { title: "flush" },
      },
      {
        // 修改密码
        path: "amendpassword",
        name: "amendpassword",
        component: () => import("@/views/AmendPassword"),
        meta: { title: "amendpassword" },
      },
      {
        // 用户信息
        path: "myinformation",
        name: "myinformation",
        component: () => import("@/views/MyInformation"),
        meta: { title: "myinformation" },
      },
    ],
  },
  {
    //登录页
    path: "/login",
    name: "login",
    component: LoginView,
  },
  {
    //路由不存在页面
    path: "/404",
    name: "404",
    component: _404View,
  },
  {
    //匹配不存在的任何路由
    path: "/:path(.*)+",
    redirect: "/404",
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 设置路由守卫
router.beforeEach((to, from) => {
  let token = Cookie.get("token");
  let path = from.path;
  if (!token && to.name != "login") {
    router.replace({ name: "login", query: { back: path } });
  }
});

export default router;
